package org.xlx.xlx_oa.role_user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xlx.xlx_oa.common.BaseEntity;
import org.xlx.xlx_oa.common.BusinessException;
import org.xlx.xlx_oa.common.Constant;
import org.xlx.xlx_oa.common.MessageTemplate;
import org.xlx.xlx_oa.common.enums.ProcessActionEnums;
import org.xlx.xlx_oa.common.enums.ProcessStatusEnums;
import org.xlx.xlx_oa.common.enums.ProcessTypeEnums;
import org.xlx.xlx_oa.common.enums.YesOrNoEnums;
import org.xlx.xlx_oa.role_user.convertor.RoleUserConvertor;
import org.xlx.xlx_oa.role_user.domain.AdmProcess;
import org.xlx.xlx_oa.role_user.domain.AdmUser;
import org.xlx.xlx_oa.role_user.domain.dto.AdmProcessDto;
import org.xlx.xlx_oa.role_user.domain.dto.AdmUserDto;
import org.xlx.xlx_oa.role_user.domain.vo.AuditVo;
import org.xlx.xlx_oa.role_user.mapper.AdmProcessMapper;
import org.xlx.xlx_oa.utils.ThreadLocalUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class AdmProcessService {
    @Autowired
    private AdmProcessMapper admProcessMapper;
    @Autowired
    private AdmUserService admUserService;
    @Autowired
    private SysNotificationService sysNotificationService;
    private final RoleUserConvertor userConvertor = RoleUserConvertor.INSTANCE;

    /**
     * 创建申请处理任务
     *
     * @param processType
     * @param applyId
     * @return
     */
    public Boolean createFirstProcess(ProcessTypeEnums processType, Long applyId) {
        //insert audit self apply
        AdmProcess admProcess = new AdmProcess();
        admProcess.setProcessStatus(ProcessStatusEnums.Completed.name());
        admProcess.setProcessType(processType.name());
        admProcess.setAction(ProcessActionEnums.Apply.name());
        admProcess.setApplyId(applyId);
        admProcess.setIsLast(YesOrNoEnums.No.name());
        Object obj = ThreadLocalUtil.get(Constant.USERID);
        Long userId = Objects.isNull(obj) ? null : Long.valueOf(obj.toString());
        admProcess.setUserId(userId);
        admProcess.setResult(ProcessStatusEnums.Approve.name());
        //insert notification for self
        String content = String.format(MessageTemplate.applyMsgForSelf, processType.getText());
        Boolean notification = sysNotificationService.createNotification(content, userId);
        if (!notification) {
            throw new BusinessException("100006", "notification create failed");
        }
        return admProcessMapper.insert(admProcess) > 0;
    }

    /**
     * 拟
     * 通用申请处理任务创建
     */
    @Transactional
    public Boolean createProcess(Long applyId, ProcessTypeEnums processType, Boolean flag) {
        // userName,level
        Object objUserName = ThreadLocalUtil.get(Constant.USERNAME);
        String userName = Objects.isNull(objUserName) ? null : objUserName.toString();
        Object objLevel = ThreadLocalUtil.get(Constant.LEVEL);
        Integer level = Objects.isNull(objLevel) ? null : Integer.valueOf(objLevel.toString());
        //create leader process
        AdmUser curLeader = admUserService.getCurLeader();
        AdmProcess admProcess = new AdmProcess();
        admProcess.setProcessStatus(ProcessStatusEnums.Progressing.name());
        admProcess.setProcessType(processType.name());
        admProcess.setAction(ProcessActionEnums.Audit.name());
        admProcess.setApplyId(applyId);
        admProcess.setUserId(curLeader.getId());
        admProcess.setResult(ProcessStatusEnums.Processing.name());
        admProcess.setOrderNo(1);
        // insert apply process
        Boolean firstProcess = this.createFirstProcess(processType, applyId);
        if (!firstProcess) {
            throw new BusinessException("110002", "apply process create failed");
        }
        //insert beAudit process
        if (level < 7) {
            //insert notification for department manager
            String content = String.format(MessageTemplate.applyMsgForAudit, userName, processType.getText());
            Boolean notification = sysNotificationService.createNotification(content, curLeader.getId());
            if (!notification) {
                throw new BusinessException("100006", "notification create failed");
            }
            if (flag) {
                //isLast,insert
                admProcess.setIsLast(YesOrNoEnums.No.name());
                admProcessMapper.insert(admProcess);
                //insert manager audit process
                AdmUser leader = admUserService.getLeader(curLeader);
                AdmProcess endProcess = new AdmProcess();
                endProcess.setProcessStatus(ProcessStatusEnums.NoBegin.name());
                endProcess.setProcessType(processType.name());
                endProcess.setAction(ProcessActionEnums.Audit.name());
                endProcess.setApplyId(applyId);
                endProcess.setUserId(leader.getId());
                endProcess.setResult(ProcessStatusEnums.Pending.name());
                endProcess.setOrderNo(2);
                endProcess.setIsLast(YesOrNoEnums.Yes.name());
                admProcessMapper.insert(endProcess);
            } else {
                //isLast,insert
                admProcess.setIsLast(YesOrNoEnums.Yes.name());
                admProcessMapper.insert(admProcess);
            }
            return false;
        } else if (level == 7) {
            //insert manager audit process
            admProcess.setIsLast(YesOrNoEnums.Yes.name());
            admProcessMapper.insert(admProcess);
            //insert notification for manager
            String content = String.format(MessageTemplate.applyMsgForAudit, userName, processType.getText());
            Boolean notification = sysNotificationService.createNotification(content, curLeader.getId());
            if (!notification) {
                throw new BusinessException("100006", "notification create failed");
            }
            return false;
        } else if (level == 8) {
            //insert self audit process
            admProcess.setProcessStatus(ProcessStatusEnums.Completed.name());
            admProcess.setResult(ProcessStatusEnums.Approve.name());
            admProcess.setIsLast(YesOrNoEnums.Yes.name());
            admProcessMapper.insert(admProcess);
            //insert notification for manager
            String content = String.format(MessageTemplate.applyMsgForManagerSelf, processType.getText());
            Boolean notification = sysNotificationService.createNotification(content, curLeader.getId());
            if (!notification) {
                throw new BusinessException("100006", "notification create failed");
            }
            return true;
        } else {
            throw new BusinessException("100005", "nonexistence user level");
        }
    }

    /**
     * 审批申请
     */
    @Transactional
    public String updateAuditProcess(AuditVo auditVo, BaseEntity baseEntity) {
        //userid,result
        String returnValue = "";
        Object objUserId = ThreadLocalUtil.get(Constant.USERID);
        Long userId = Objects.isNull(objUserId) ? null : Long.valueOf(objUserId.toString());
        String result = this.getTextByName(auditVo.getResult());
        ProcessTypeEnums typeEnums = ProcessTypeEnums.valueOf(ProcessTypeEnums.class, auditVo.getProcessType());
        //processes by applyId
        List<AdmProcess> processes = this.getProcessesByApplyId(auditVo.getProcessType(), auditVo.getApplyId());
        //self process
        AdmProcess process = null;
        //next process
        AdmProcess next = null;
        for (int i = 0; i < processes.size(); i++) {
            if (processes.get(i).getUserId().equals(userId)) {
                process = processes.get(i);
                if (YesOrNoEnums.No.name().equals(process.getIsLast())
                        && i < processes.size() - 1) {
                    next = processes.get(i + 1);
                }
                break;
            }
        }
        //update self process
        process.setResult(auditVo.getResult());
        process.setReason(auditVo.getReason());
        process.setProcessStatus(ProcessStatusEnums.Completed.name());
        this.updateProcessByApplyId(process);
        //if refuse or isLast
        if (ProcessStatusEnums.Refuse.name().equals(process.getResult())
                || YesOrNoEnums.Yes.name().equals(process.getIsLast())) {
            if (next != null) {
                //cancel next audit
                next.setProcessStatus(ProcessStatusEnums.Cancel.name());
                this.updateProcessByApplyId(next);
            }
        }
        if (YesOrNoEnums.No.name().equals(process.getIsLast())) {
            if (ProcessStatusEnums.Refuse.name().equals(process.getResult())) {
                //create notification for apply
                String apply = String.format(MessageTemplate.auditEndMsgForApplier, typeEnums.getText(), result);
                sysNotificationService.createNotification(apply, baseEntity.getCreatedId());
                //create notification for audit
                String audit = String.format(MessageTemplate.auditEndMsgForSelf, baseEntity.getCreatorName(),
                        typeEnums.getText(), result);
                sysNotificationService.createNotification(audit, userId);
                returnValue = process.getResult();
            } else {
                //create notification for apply
                String apply = String.format(MessageTemplate.auditMsgForApplier, typeEnums.getText(), result);
                sysNotificationService.createNotification(apply, baseEntity.getCreatedId());
                //create notification for audit
                String audit = String.format(MessageTemplate.auditMsgForSelf, baseEntity.getCreatorName(),
                        typeEnums.getText(), result);
                sysNotificationService.createNotification(audit, userId);
                returnValue = ProcessStatusEnums.Progressing.name();
            }
        } else {
            //create notification for apply
            String apply = String.format(MessageTemplate.auditEndMsgForApplier, typeEnums.getText(), result);
            sysNotificationService.createNotification(apply, baseEntity.getCreatedId());
            //create notification for audit
            String audit = String.format(MessageTemplate.auditEndMsgForSelf, baseEntity.getCreatorName(),
                    typeEnums.getText(), result);
            sysNotificationService.createNotification(audit, userId);
            returnValue = process.getResult();
        }
        return returnValue;
    }

    /**
     * 根据申请信息获取处理任务集合
     *
     * @param processType
     * @param applyId
     * @return
     */
    public List<AdmProcess> getProcessesByApplyId(String processType, Long applyId) {
        QueryWrapper<AdmProcess> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AdmProcess::getProcessType, processType)
                .eq(AdmProcess::getApplyId, applyId)
                .orderByAsc(AdmProcess::getOrderNo);
        return admProcessMapper.selectList(queryWrapper);
    }

    /**
     * 更新处理任务
     *
     * @param admProcess
     * @return
     */
    public Boolean updateProcessByApplyId(AdmProcess admProcess) {
        return admProcessMapper.updateById(admProcess) > 0;
    }

    /**
     * 获得审核结果code的文本
     *
     * @param name
     * @return
     */
    public String getTextByName(String name) {
        ProcessStatusEnums enums = ProcessStatusEnums.valueOf(ProcessStatusEnums.class, name);
        return enums.getText();
    }

    /**
     * 获取待审批applyId
     */
    public List<AdmProcess> getApplyList(String processType) {
        Object obj = ThreadLocalUtil.get(Constant.USERID);
        Long userId = Objects.isNull(obj) ? null : Long.valueOf(obj.toString());
        QueryWrapper<AdmProcess> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(AdmProcess::getProcessType, processType)
                .eq(AdmProcess::getUserId, userId)
                .eq(AdmProcess::getAction, ProcessActionEnums.Audit.name());
        List<AdmProcess> admProcesses = admProcessMapper.selectList(queryWrapper);
        return admProcesses;
    }

    /**
     * 获取process处理任务
     *
     * @param applyId
     * @param processType
     * @return
     */
    public List<AdmProcessDto> getListByApplyId(Long applyId, String processType) {
        QueryWrapper<AdmProcess> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(AdmProcess::getApplyId, applyId)
                .eq(AdmProcess::getProcessType, processType)
                .orderByAsc(AdmProcess::getId);
        List<AdmProcess> admProcesses = admProcessMapper.selectList(wrapper);
        List<AdmProcessDto> processDtos = userConvertor.convertToProcessDtoList(admProcesses);
        processDtos.forEach(processDto -> this.supplyProcessDto(processDto));
        return processDtos;
    }

    /**
     * processDto 补全
     *
     * @param processDto
     */
    public void supplyProcessDto(AdmProcessDto processDto) {
        AdmUserDto detail = admUserService.getDetail(processDto.getUserId());
        processDto.setFirstName(detail.getFirstName());
        processDto.setMiddleName(detail.getMiddleName());
        processDto.setLastName(detail.getLastName());
        processDto.setPositionTitle(detail.getPositionTitle());
        processDto.setDepartmentTitle(detail.getDepartmentTitle());
        ProcessStatusEnums resultEnums
                = ProcessStatusEnums.valueOf(ProcessStatusEnums.class, processDto.getResult());
        processDto.setResultName(resultEnums.getText());
        ProcessStatusEnums statusEnum
                = ProcessStatusEnums.valueOf(ProcessStatusEnums.class, processDto.getProcessStatus());
        processDto.setProcessStatusName(statusEnum.getText());
        ProcessTypeEnums typeEnums
                = ProcessTypeEnums.valueOf(ProcessTypeEnums.class, processDto.getProcessType());
        processDto.setProcessTypeName(typeEnums.getText());
        ProcessActionEnums actionEnums
                = ProcessActionEnums.valueOf(ProcessActionEnums.class, processDto.getAction());
        processDto.setActionName(actionEnums.getText());
    }
}
